package com.study.rocketmq;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wanghuilong
 * @date 2020/12/16 4:50 下午
 */
public class SyncProducer {

    public static void main(String[] args) throws MQClientException, UnsupportedEncodingException
            , RemotingException, InterruptedException, MQBrokerException {
        AtomicInteger atomicInteger = new AtomicInteger(0);
        atomicInteger.addAndGet(1);

        //Instantiate with a producer group name.
        DefaultMQProducer producer = new DefaultMQProducer("test_group1");
        // Specify name server addresses.
        producer.setNamesrvAddr("10.211.55.3:9876;10.211.55.4:9876");
        producer.setSendMsgTimeout(10000);
        //Launch the instance.
        producer.start();
        try {
            for (int i = 0; i < 100; i++) {
                //Create a message instance, specifying topic, tag and message body.
                Message msg = new Message("TopicTest" /* Topic */,
                        "TagA" /* Tag */,
                        "KeyA", /*keys*/
                        ("Hello RocketMQ " +
                                i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
                );
                //Call send message to deliver message to one of brokers.
                SendResult sendResult = producer.send(msg);
                System.out.printf("%s%n", sendResult);
            }
            //Shut down once the producer instance is not longer in use.
        } catch (Exception e) {
            e.printStackTrace();
        }
        producer.shutdown();

    }

}
